/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-07-17     Administrator       the first version
 */

#include <stdint.h>
#include <stdio.h>
#include <rtthread.h>
#include <rtdevice.h>
#include <u8g2_port.h>

static u8g2_t u8g2;
extern float CHO_Data;
extern struct rt_sensor_data temp_data;
extern struct rt_sensor_data  humi_data;
static char datatmp[40];
static void ssd1306_entry(void* params)
{
    while(1)
    {
        u8g2_ClearBuffer(&u8g2);
        u8g2_SetFont(&u8g2, u8g2_font_wqy12_t_gb2312a);
        u8g2_DrawUTF8(&u8g2, 24, 12, "RA6M4环境采集");
        u8g2_DrawUTF8Line(&u8g2, 0, 20, 1, "----------------------------", 0, 0);
        snprintf(datatmp, sizeof(datatmp) - 1, "甲醛: %fmg/m^3", CHO_Data);
        u8g2_DrawUTF8(&u8g2, 4, 32, datatmp);
        snprintf(datatmp,sizeof(datatmp)-1,"温度:%d.%d 摄氏度",temp_data.data.temp/10,temp_data.data.temp%10);
        u8g2_DrawUTF8(&u8g2, 4, 44, datatmp);
        snprintf(datatmp,sizeof(datatmp)-1,"湿度:%d%%",humi_data.data.humi/10);
        u8g2_DrawUTF8(&u8g2, 4, 56, datatmp);
        u8g2_SendBuffer(&u8g2);
        //rt_hw_us_delay(500000);
        rt_thread_delay(rt_tick_from_millisecond(500));
    }

}

static int ssd1306_thread(void)
{
    rt_err_t ret = RT_EOK;
    // Initialization
    u8g2_Setup_ssd1306_i2c_128x64_noname_f( &u8g2, U8G2_R0, u8x8_byte_rtthread_hw_i2c, u8x8_gpio_and_delay_rtthread);
    u8g2_InitDisplay(&u8g2);
    u8g2_SetPowerSave(&u8g2, 0);

    rt_thread_t thread = rt_thread_create("ssd1306_u8g2", ssd1306_entry, RT_NULL, 1024, 14, 14);
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
    else
    {
        ret = RT_ERROR;
    }
    return ret;
}

INIT_APP_EXPORT(ssd1306_thread);
